package com.twq.oo.traits

/**
 * Created by tangweiqun on 2017/11/28.
 * trait叠加修饰
 */
object StackableModifications {
  def main(args: Array[String]): Unit = {
    val queue = new BasicIntQueue
    queue.put(10)
    println(queue.get()) //10

    val myQueue = new MyQueue
    myQueue.put(10)
    println(myQueue.get()) //20

    val queue1 = new BasicIntQueue with Doubling
    queue1.put(10)
    println(queue1.get()) //20

    //先过滤再增加
    val queue2 = (new BasicIntQueue
      with Incrementing with Filtering) //先执行Filtering 再执行 Incrementing
    queue2.put(-1)
    queue2.put(0)
    queue2.put(1)
    println(queue2.get()) //1
    println(queue2.get()) //2

    //先增加再过滤
    val queue3 = (new BasicIntQueue
      with Filtering with Incrementing) //Incrementing 再执行 Filtering
    queue3.put(-1)
    queue3.put(0)
    queue3.put(1)
    println(queue3.get()) //0
    println(queue3.get()) //1
    println(queue3.get()) //2
  }
}

abstract class IntQueue {
  def get(): Int

  def put(x: Int)
}

import scala.collection.mutable.ArrayBuffer

class BasicIntQueue extends IntQueue {
  private val buf = new ArrayBuffer[Int]

  def get() = buf.remove(0)

  def put(x: Int) = {
    buf += x
  }
}

trait Doubling extends IntQueue {
  abstract override def put(x: Int) = {
    super.put(2 * x)
  }
}

trait Incrementing extends IntQueue {
  abstract override def put(x: Int) = {
    super.put(x + 1)
  }
}

trait Filtering extends IntQueue {
  abstract override def put(x: Int) = {
    if (x >= 0) super.put(x)
  }
}

class MyQueue extends BasicIntQueue with Doubling


